<template>
    <div class="app-container">
        <div class="search-container">
            <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
                <el-form-item label="计费时间段" prop="">
                    <el-date-picker v-model="dateRange" :shortcuts="$shortcuts()" :unlink-panels="true"
                                    end-placeholder="结束日期" range-separator="截止"
                                    start-placeholder="开始日期" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
                                    @change="handleQuery"></el-date-picker>
                </el-form-item>
                <el-form-item label="项目名称" prop="itemName">
                    <el-input
                        v-model="queryParams.itemName"
                        clearable
                        placeholder="请输入项目名称"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item v-if="isShowQuery" label="患者姓名" prop="remarks">
                    <el-input
                        v-model="queryParams.name"
                        clearable
                        placeholder="请输入患者姓名"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item>
                    <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
                </el-form-item>
            </el-form>
        </div>
        <el-row :gutter="10" class="mb8">
            <!--            <el-col :span="1.5">-->
            <!--                <el-button-->
            <!--                    type="primary"-->
            <!--                    plain-->
            <!--                    @click="handleAdd"-->
            <!--                    v-hasPerm="['business:inpBillDetail:add']"-->
            <!--                >-->
            <!--                    <template-->
            <!--                        #icon>-->
            <!--                        <i-ep-plus/>-->
            <!--                    </template>-->
            <!--                    新增-->
            <!--                </el-button>-->
            <!--            </el-col>-->
        </el-row>
        <el-form ref="formRef" :model="form">
            <el-table v-adaptive="340" :border="true" :data="form.refundItemList"
                      :header-cell-style="$headerCellStyle" :stripe="true" highlight-current-row>
                <el-table-column :align="'center'" fixed="left" label="费用发生时间" prop="medicalVerifyTime"
                                 width="170">
                    <template #default="scope">
                        <span class="ys-css">{{ $parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                    </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip='true' fixed="left" label="医嘱内容"
                                 prop="orderText" width="170">
                    <template #default="scope">
                        <span class="ys-css">{{ scope.row.orderText }}</span>
                    </template>
                </el-table-column>
                <el-table-column :align="'center'" fixed="left" label="项目类型" prop="itemClass" width="70">
                    <template #default="scope">
                        <dict-data-tag :options="dictDataMap['bill_item_class_dict']" :value="scope.row.itemClass"/>
                    </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" fixed="left" label="项目名称"
                                 prop="itemName"
                                 width="170">
                    <template #default="scope">
                        <span class="ys-css">{{ scope.row.itemName }}</span>
                    </template>
                </el-table-column>
                <el-table-column :align="'left'" fixed="left" header-align="center" label="数量" prop="amount"
                                 :show-overflow-tooltip="true" width="80px">
                    <template #default="scope">
                    <span
                        class="ys-css">{{
                            parseFloat(scope.row.amount.toString()).toFixed(0)
                        }}</span>{{ scope.row.unitsName }}
                    </template>
                </el-table-column>
                <el-table-column v-if="isReturnOk" :align="'left'" fixed="left" header-align="center" label="退费数量"
                                 :show-overflow-tooltip="true" prop="returnAmountInput" width="160">
                    <template #default="scope">
                        <el-input v-if="isReturnOk" v-model="scope.row.returnAmountInput"
                                  :disabled="scope.row.remainingAmountShow === 0" class="groupNumber"
                                  prop="groupNumber" @blur="returnAmountInputBlur(scope.$index, scope.row)">
                            <template #append >{{ scope.row.unitsName }}</template>
                        </el-input>
                        <span v-else>{{ scope.row.returnAmountInput }}&nbsp;{{ scope.row.unitsName }}</span>
                    </template>
                </el-table-column>
                <el-table-column :align="'left'"
                                 fixed="left"
                                 label="已申请退费数量"
                                 prop="returnAmountShow" width="110">
                    <template #default="scope">
                                        <span
                                            class="ret-ys-css">{{ scope.row.returnAmountShow }}</span>{{
                            scope.row.unitsName
                        }}
                    </template>
                </el-table-column>
                <el-table-column :align="'left'" fixed="left" header-align="center" label="剩余数量"
                                 :show-overflow-tooltip="true" prop="remainingAmountShow" width="80">
                    <template #default="scope">
                    <span
                        class="ys-css">{{ scope.row.remainingAmountShow }}</span>{{ scope.row.unitsName }}
                    </template>
                </el-table-column>
                <el-table-column :align="'right'" header-align="center" label="单价(元)" prop="itemPrice" width="110">
                    <template #default="scope">
                        <span class="ys-css">{{ parseFloat(scope.row.itemPrice.toString()).toFixed(2) }}</span>元
                    </template>
                </el-table-column>
                <el-table-column :align="'right'" header-align="center" label="实收费用(元)" prop="charges" width="110">
                    <template #default="scope">
                        <span class="ys-css">{{ parseFloat(scope.row.charges.toString()).toFixed(2) }}</span>元
                    </template>
                </el-table-column>
                <el-table-column :align="'center'" label="费用来源" prop="sourceType"/>
                <el-table-column :align="'center'" label="项目规格" prop="itemSpec" width="120"/>
                <el-table-column :align="'center'" label="开单科室" prop="applyDeptName" width="100"/>
                <el-table-column :align="'center'" label="开单医生" prop="applyDoctorName" width="100"/>
                <el-table-column :align="'center'" label="执行科室" prop="implementDeptName" width="100"/>
                <el-table-column :align="'center'" label="收据分类" prop="classOnInpName"/>
                <el-table-column :align="'center'" label="患者所在科室" prop="deptStayedName" width="100"/>
                <el-table-column :align="'center'" label="患者所在病区" prop="wardCodeName" width="100"/>
                <el-table-column :align="'center'" label="医保是否上传" prop="isUpload" width="100">
                    <template #default="scope">
                        <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.isUpload"/>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
    </div>
</template>
<script lang="ts" setup>
import {useUserStoreHook} from "@/store/modules/user";
import {refundItemListOk, refundQueryList} from "@/api/hospitalization/inpBillDetail.ts";

import {useDictStoreHook} from "@/store/modules/dict";

const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'tally_subject_dict', 'bill_item_class_dict',
    'inp_rcpt_fee_dict', 'sys_yes_no', 'reck_item_class_dict', 'mr_fee_class_dict'))

const {proxy} = getCurrentInstance() as any;
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const queryParamsRef = ref()
const inpBillDetailList = ref([]);
const showSearch = ref(true);
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);
const emits = defineEmits(["submitForm"])
const props = defineProps({
    isShowQuery: {
        type: Boolean,
        default: true
    },
    isReturnOk: {
        type: Boolean,
        default: true
    }
})
const queryParams = ref({
    patientId: "",
    visitId: "",
    orgId: userInfo.orgId,
    name: "",
    itemName: '',
    itemClassNotIn: ['A', 'B'],
    // 数量 >0  0 大于 ；1小于
    amountGtZero: '0'
})

const form = ref<any>({
    // 退非数量list
    refundItemList: []
})

/**
 * 父组件加载初始化方法
 */
function initOpen(obj: any) {
    queryParams.value.visitId = obj.visitId;
    queryParams.value.patientId = obj.patientId;
    getList()
}

/** 查询住院费用inp_bill_detail列表 */
function getList() {
    refundQueryList(proxy.$addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
        form.value.refundItemList = response.data;
        form.value.refundItemList.forEach((item: any) => {
            let refundAmount: number = 0
            if (item.retVsInpBillList) {
                item.retVsInpBillList.forEach((retItem: any) => {
                    refundAmount += Number(retItem.amount)
                })
            }
            item.returnAmountShow = -Number(refundAmount)
            item.remainingAmountShow = Number(item.amount) + Number(refundAmount)
            // item.returnAmountInput = 0
        })
    });
}

/**
 * 退药数量输入框焦点消失事件
 */
function returnAmountInputBlur(index: number, row: any) {
    const indexS: number = Number(index) + 1
    if (row.returnAmountInput > row.remainingAmountShow) {
        return ElMessage.error("第" + indexS + "行，项目：【" + row.itemName + "】,申请退费数量大于开单数量，请重新填写【退费数量】")
    }
}

/** 搜索按钮操作 */
function handleQuery() {
    getList()
}

function submitForm() {
    let refundItemList: any = []
    for (let index = 0; index < form.value.refundItemList.length; index++) {
        const item = form.value.refundItemList[index]
        const indexS: number = Number(index) + 1
        if (item.returnAmountInput !== undefined && item.returnAmountInput > item.remainingAmountShow) {
            return ElMessage.error("第" + indexS + "行，项目：【" + item.itemName + "】,申请退费数量大于开单数量，请重新填写【退费数量】")
        }
        let retVsInpBill: any = {
            inpBillDetailId: item.inpBillDetailId,
            returnAmount: item.returnAmountInput,
            patientId: item.patientId,
            visitId: item.visitId,
            orgId: item.orgId
        }
        refundItemList.push(retVsInpBill)
    }
    let refundItemSubmitList = refundItemList.filter((item: any) => item.returnAmount != 0 && item.returnAmount != null)
    if (refundItemSubmitList.length <= 0) {
        return ElMessage.error("没有需要申请退非的项目，不能提交。")
    }
    ElMessageBox.confirm('确定要提交退费申请吗？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        const form = {
            retVsInpBillList: refundItemSubmitList,
            orgId: userInfo.orgId,
            visitId: queryParams.value.visitId,
            patientId: queryParams.value.patientId
        }
        refundItemListOk(form).then(() => {
            ElMessage.success("提交成功");
            getList()
        })
    }).catch(() => {
    })
}


/** 重置按钮操作 */
function resetQuery() {
    queryParamsRef.value.resetFields()
    dateRange.value = [date + "00:00:00", date + "23:59:59"]
    handleQuery();
}


/** 清空 */
function empty() {
    queryParamsRef.value.resetFields()
    dateRange.value = [date + "00:00:00", date + "23:59:59"]
    form.value.refundItemList = []
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('business/inpBillDetail/export', {
        ...queryParams.value
    }, `inpBillDetail_${new Date().getTime()}.xlsx`)
}


defineExpose({
    initOpen,
    submitForm,
    empty
})
getList();
</script>

